<template>
  <view>
    <u-modal
      :show="modalShow"
      @close="modalShow = false"
      @confirm="handleConfirm"
      :showConfirmButton="autoSwitch"
      :confirmText="autoSwitch ? '确认登录' : '确认'"
      :closeOnClickOverlay="!autoSwitch"
    >
      <view class="w-full flex flex-col">
        <view class="modal-title">当前账号已注册地区/单位</view>
        <scroll-view scroll-y class="max-h-65vh">
          <radio-group @change="handleSelectTenant">
            <label
              class="flex items-center item"
              v-for="(item, index) in tenantList"
              :key="item.id"
              :class="{ active: index === currentSelect }"
            >
              <view>
                <radio
                  :value="item.id"
                  :checked="index === currentSelect"
                  class="transform scale-70"
                />
              </view>
              <view>{{ item.shortName }}</view>
            </label>
          </radio-group>
        </scroll-view>
      </view>
    </u-modal>

    <!--  slot  -->
    <slot name="default" :tenant="currentTenant"></slot>
  </view>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import { appStore, userStore } from '@/store/modules'
import { showModal, showToast } from '@/utils/helper/uniHelper'
import type { PaasTenant } from '@/api/sys/model/authModel'
import { isEmpty } from 'lodash-es'

@Component({ name: 'MyTenant' })
export default class MyTenant extends Vue {
  @Prop({ type: Boolean, default: null }) value!: boolean
  @Prop({ type: Boolean, default: true }) autoSwitch!: boolean

  get initTenantId() {
    return appStore.initDefaultTenant
  }

  @Watch('initTenantId', { immediate: true })
  onInitTenantIdChange(val: string) {
    this.initSelect()
  }

  public currentSelect: number = -1

  get currentTenant() {
    return this.tenantList[this.currentSelect] ?? {}
  }

  @Watch('currentTenant', { immediate: true })
  onCurrentSelectChange(val: number) {
    !isEmpty(val) && this.$emit('tenantChange', val)
  }

  initSelect() {
    this.currentSelect = this.tenantList.findIndex(
      (item) => item.id === this.initTenantId
    )
  }

  public innerValue: boolean = false

  get modalShow() {
    return !this.autoSwitch ? this.value : this.innerValue
  }

  set modalShow(value: boolean) {
    !this.autoSwitch ? this.$emit('input', value) : (this.innerValue = value)
  }

  public tenantList: PaasTenant[] = []

  onReady() {
    const tenantList = userStore.authInfo?.tenantList ?? []
    if (!tenantList.length) {
      return showModal('请前往注册或联系管理员初始化账号')
    }

    this.tenantList = tenantList
    this.initSelect()

    // 自动处理
    if (this.autoSwitch) {
      // token没带租户id，且拥有多个租户，则显示弹窗
      if (this.tenantList.length > 1 && !userStore.authInfo?.tenantId) {
        this.innerValue = true
      } else if (userStore.authInfo?.tenantId) {
        this.currentSelect =
          this.tenantList.findIndex(
            (item) => item.id === userStore.authInfo?.tenantId
          ) || 0
        this.handleConfirm(false)
      } else {
        appStore.setSelectTenant(this.tenantList[0].id)
        this.currentSelect = 0
        this.handleConfirm(true)
      }
    }
  }

  handleSelectTenant({ detail }: AnyObject) {
    console.log(`当前选择的租户：${detail.value}`)
    appStore.setSelectTenant(detail.value)

    // todo:如果打开弹窗切换后没有点击确认按钮？如下暂时解决问题
    if (!this.autoSwitch) {
      this.handleConfirm(true)
    }
  }

  async handleConfirm(autoLogin = true) {
    if (this.currentSelect < 0) {
      return showToast({ title: '请选择其中一项进行登录' })
    }
    this.modalShow = false

    if (autoLogin) {
      try {
        await userStore.Login({ loginType: 3 })
      } catch (e: any) {
        await showModal({
          content: '切换失败，点击确认后将退出登录，请前往注册该地区/单位'
        })
        return userStore.Logout()
      }
    }

    userStore.setHasLogin(true)
    this.$emit('login', this.tenantList[this.currentSelect])
  }
}
</script>

<style lang="scss" scoped>
.modal-title {
  @apply text-28rpx text-[#999] mb-30rpx text-center;
}

.item {
  @apply my-20rpx bg-[#8080801A] p-10rpx;

  &.active {
    @apply bg-[#0052D91A] text-[#0052D9];
  }
}
</style>
